﻿using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Zijian666
{
    /// <summary>
    /// 套接字扩展方法
    /// </summary>
    public static class SocketExtensions
    {
        /// <summary>
        /// 监听数据传入
        /// </summary>
        public static void ListenReceive(this Socket socket, EventHandler<string> receiver, CancellationToken token)
            => _ = new SocketStringReader(socket, receiver, token);

        /// <summary>
        /// 发送字符串
        /// </summary>
        public static int Send(this Socket socket, string str) =>
            socket.Send(Encoding.UTF8.GetBytes(str + SocketStringReader.SPLITION), SocketFlags.None);
        /// <summary>
        /// 发送一行字符串
        /// </summary>
        public static int SendLine(this Socket socket, string str) =>
            Send(socket, str + "\n");
        /// <summary>
        /// 检查套接字连接是否存活
        /// </summary>
        public static bool CheckAlive(this Socket socket)
        {
            try
            {
                socket.Send("");
                return true;
            }
            catch
            {
                return socket?.Connected ?? false;
            }
        }
    }
}
